package io.nio;

import framework.AbstractTest;
import utils.Log;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import static java.lang.System.in;

/**
 * Created by shane on 2018/6/09.
 *
 * 内存映射文件允许我们创建和修改那些因为太大而不能放入内存的文件
 */
public class LargeMappedFiles extends AbstractTest {
    protected static final String TAG = LargeMappedFiles.class.getName();
    static final int SIZE = 0X8FFFFFF; // 128MB

    
    @Override
    public void test(String[] args) {
        super.test(args);

        String mmapFile = getDefMmapFile(args);

        try {
            String file = "/Users/shane/test/mmap.pdf";
            MappedByteBuffer out = new RandomAccessFile(mmapFile, "rw").getChannel().map(
                    FileChannel.MapMode.READ_WRITE, 0, SIZE);

            for (int i = 0; i < SIZE; i++) {
                out.put((byte)'x');
            }
            Log.vn("Finished Writing!");

            for (int i = SIZE/2; i < SIZE/2+6; i++) {
                Log.v((char)out.get(i));
            }

            Log.vn("Finished Reading!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }

}
